//
//  XYTNetRequest.m
//  XYTPayOrderSystem
//
//  Created by wupeng on 2017/8/23.
//  Copyright © 2017年 wupeng. All rights reserved.
//

#import "XYTNetRequest.h"

static dispatch_once_t onceToken;
static XYTNetRequest *_sharedManager = nil;

@implementation XYTNetRequest

+ (instancetype)sharedManager {
    
    dispatch_once(&onceToken, ^{
        _sharedManager = [[self alloc] init];
    });
    
    return _sharedManager;
}

- (instancetype)init{
    //设置服务器根地址
    _sharedManager = [[XYTNetRequest alloc] initWithBaseURL:[NSURL URLWithString:BaseUrl]];
    
    AFSecurityPolicy * securityPolicy = [AFSecurityPolicy  defaultPolicy];
    
    [_sharedManager setSecurityPolicy:securityPolicy];
    //设置超时
    _sharedManager.requestSerializer.timeoutInterval = TimeoutInterval;
    //设置请求数据
    _sharedManager.requestSerializer = [AFHTTPRequestSerializer serializer];//发送http数据
    //设置相应数据
    _sharedManager.responseSerializer = [AFHTTPResponseSerializer serializer];//响应http数据
    //        _sharedManager.responseSerializer = [AFJSONResponseSerializer serializer]; //响应json数据,报3804错误
    //设置acceptableContentTypes  如果不加@"text/html"会报-1016错误
    _sharedManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", nil];
    return _sharedManager;
    
}

+ (NSURLSessionDataTask *)POST:(NSString *)URLString
                        parameters:(id)parameters
                         isNeedKey:(BOOL)isNeedKey
                           success:(void (^)(id responseObject))success
                           failure:(void (^)(NSString *errorMsg))failure{
    XYTNetRequest *manager = [self sharedManager];
    NSLog(@"HTTP:\n%@%@",manager.baseURL,URLString);
    //设置 header
    [manager.requestSerializer setValue:[XYTUserInfoManager sharedManager].token.length > 0 ? [XYTUserInfoManager sharedManager].token:@"" forHTTPHeaderField:@"xytkj-auth-token"];
    //处理参数
    NSDictionary *params = [self dealWithParams:parameters isNeedKey:isNeedKey];
    XYTWeakSelf(self)
    return [manager POST:URLString parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        XYTStrongSelf(weakSelf)
        NSError *error = nil;
        id jsonObject = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:&error];
        if (error) {
            [strongSelf showAlertWithTitle:@"数据解析错误"]; return;
        }
        NSLog(@"server respone  JSON:\n%@",jsonObject);
        NSDictionary *responseDic = (NSDictionary *)responseObject;
        XYTBaseModel *baseModel = [XYTBaseModel mj_objectWithKeyValues:responseDic];
        //接口成功
        if ([baseModel.code isEqualToString:@"200"]) {
            //将result抛给上层
            success(baseModel.result);
        }
        //token失效
        else if ([baseModel.code isEqualToString:@"400001"]||[baseModel.message isEqualToString:@"Token失效!"]){
            [UIView hideHUD];
            [strongSelf gotoLoginAgain];//去重新登录
        }
        //接口失败
        else {
            failure(baseModel.message);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        XYTStrongSelf(weakSelf)
        [UIView hideHUD];
        //todo 统一处理错误 不往上层抛错误
        NSString *responseString =  [[NSString alloc] initWithData:(NSData *)error.userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] encoding:NSUTF8StringEncoding];
        NSLog(@"server respone  Error JSON:\n%@",responseString);
        //提示错误信息
        [strongSelf showAlertWithTitle:@"服务器响应失败"];
    }];
}

+ (NSDictionary *)dealWithParams:(id)parameters isNeedKey:(BOOL)isNeedKey{
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    if (isNeedKey) {
        [params xyt_setObj:AppKey forKey:@"appKey"];
        [params xyt_setObj:AppSecret forKey:@"appSecret"];
    }
    if (parameters && [parameters isKindOfClass:[NSDictionary class]]) {
        [params setValuesForKeysWithDictionary:parameters];
    }
    return params;
}

+ (NSURLSessionDataTask *)uploadImage:(NSData *)imageData
                                 POST:(NSString *)URLString
                           parameters:(id)parameters
                            isNeedKey:(BOOL)isNeedKey
                              success:(void (^)(id responseObject))success
                              failure:(void (^)(NSString *errorMsg))failure{
    //设置请求头
    NSDictionary *headerDic = (NSDictionary *)parameters;
    NSString *urlStr = [BaseUrl stringByAppendingString:URLString];
    NSURL *URL = [NSURL URLWithString:urlStr];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
    [request setHTTPMethod:@"POST"];
    for (NSString *key in headerDic) {
        [request setValue:headerDic[key] forHTTPHeaderField:key];
    }
    //添加token
    [request setValue:[XYTUserInfoManager sharedManager].token.length > 0 ? [XYTUserInfoManager sharedManager].token:@"" forHTTPHeaderField:@"xytkj-auth-token"];
    //设置请求体
    [request setHTTPBody:imageData];
    
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
    XYTWeakSelf(self)
    NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
        XYTStrongSelf(weakSelf)
        if (error) {
            NSLog(@"Error: %@", error);
        } else {
            NSError *error = nil;
            id jsonObject = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:&error];
            if (error) {
                [strongSelf showAlertWithTitle:@"数据解析错误"]; return;
            }
            NSLog(@"server respone  JSON:\n%@",jsonObject);
            NSDictionary *responseDic = (NSDictionary *)responseObject;
            XYTBaseModel *baseModel = [XYTBaseModel mj_objectWithKeyValues:responseDic];
            //接口成功
            if ([baseModel.code isEqualToString:@"200"]) {
                success(baseModel.result);//将result抛给上层
            }
            //token失效
            else if ([baseModel.code isEqualToString:@"400001"]){
                [strongSelf gotoLoginAgain];
            }
            //接口失败
            else {
                failure(baseModel.message);
            }
        }
    }];
    [dataTask resume];
    return dataTask;
}

+ (void)gotoLoginAgain{
    //清空用户信息
    [[XYTUserInfoManager sharedManager] clearUserInfo];
    //去登录
    XYTLoginRegisterViewController *loginVC = [[XYTLoginRegisterViewController alloc] init];
    [[self getCurrentViewController].navigationController pushViewController:loginVC animated:YES];
}

@end
